package Share;

import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;

public class SecureInputStream extends InputStream {
	
	private InputStream stream;
	private MessageDigest digest;
	
	public SecureInputStream(InputStream stream)
	{
		this.stream = stream;
		try {
			digest = MessageDigest.getInstance("SHA-512");
		} catch (NoSuchAlgorithmException e) {

		}
	}
	
	public void SetCipher(Cipher cipher) throws IOException
	{
		this.stream = new CipherInputStream(stream, cipher);
	}

	@Override
	public int read() throws IOException {
		
		int b = stream.read();
		digest.update((byte)b);
		
		return b;
	}
	
	public byte[] getHash()
	{
		return digest.digest();
	}
	
	public void startHash()
	{
		digest.reset();
	}
	
	public byte[] getAndCheckHash() throws IOException
	{
		byte[] hash = new byte[64];
		stream.read(hash);
		
		byte[] d = digest.digest();
		return Util.compareByteArray(hash, d) ? hash : null;
				
	}
	
	public Boolean checkHash() throws IOException
	{
		byte[] hash = new byte[64];
		stream.read(hash);

		byte[] d = digest.digest();
		return Util.compareByteArray(hash, d);
	}
}
